package com.heima.search.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es文章分页检索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        ApUser apuser = ApThreadLocalUtil.getUser();

        //异步调佣 保存搜索记录
        if (apuser != null && dto.getFromIndex() == 0) {
            Integer userId = apuser.getId();
            apUserSearchService.insert(dto.getSearchWords(),userId);
        }

        //2.创建搜索请求对象，并且指定索引库
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键字查询
        if (dto.getSearchWords() != null) {
            boolQueryBuilder.must(QueryBuilders
                    .matchQuery("all", dto.getSearchWords()));
        }
        //小于最小时间
        if (dto.getMinBehotTime() != null) {
            boolQueryBuilder.filter(QueryBuilders
                    .rangeQuery("publishTime")
                    .lte(dto.getMinBehotTime()));
        }
        searchRequest.source().query(boolQueryBuilder);
        //分页
        searchRequest.source().from(0).size(dto.getPageSize());
        //排序
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //高亮
        HighlightBuilder hightBuilder = new HighlightBuilder();
        hightBuilder.field("title");
        hightBuilder.requireFieldMatch(false);
        hightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        hightBuilder.postTags("</font>");
        searchRequest.source().highlighter(hightBuilder);
        //1.调用es的搜索api
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //3. 结果封装
        return result(response);

    }
    /**
     * 抽取的封装结果的方法
     * @param response
     * @return
     */
    private ResponseResult result(SearchResponse response) {
        List<Map> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取查询结果，返回是map集合
            Map<String, Object> map = hit.getSourceAsMap();
            //高亮数据封装
            //如果高亮域中有值
            if (hit.getHighlightFields().size() > 0) {
                //取出高亮域
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if (titles.length > 0) {
                    //把高亮之后的h_tile=<font>测试</font>
                    map.put("h_title", titles[0].toString());
                }
            } else {
                //表示没有高亮域，我们则把h_title=测试
                map.put("h_title", map.get("title"));
            }
            //把获取的结果封装到list
            list.add(map);
        }
        return  ResponseResult.okResult(list);
    }
}